package com.cc.visitor.controller;

import com.cc.alltype.BusinessException;
import com.cc.alltype.DatetimeUtils;
import com.cc.alltype.ResponseResult;
import com.cc.alltype.TimeMeasurementUnit;
import com.cc.visitor.entity.Visit;
import com.cc.visitor.entity.api.GetMonthList8OpenId;
import com.cc.visitor.enums.VisitProgress;
import com.cc.visitor.service.VisitService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author chanchaw
 * @create 2024-09-27 12:12
 */
@CrossOrigin
@RestController
@RequestMapping("/visit")
public class VisitController {
    @Autowired
    private VisitService service;
    @PostMapping("/checkWithinTime")
    public ResponseResult checkWithinTime(@RequestBody String visitorUnionId) {
        List<Visit> visitList = service.checkWithinTime(visitorUnionId);
        if(visitList == null || visitList.size() == 0) return ResponseResult.ok();

        // 存储过程 usp_getVisitWithinTime 中在字段 remark 构建了给用户查看的提示文案
        // 计算提示用户剩余时长
        Visit visit = visitList.get(0);
        if(visit == null) return ResponseResult.ok();
        LocalDateTime createTime = visit.getCreateTime();
        if(createTime == null) return ResponseResult.ok();
        Long durationTillNow = DatetimeUtils.getDurationTillNow(createTime, TimeMeasurementUnit.MINUTE);
        String msg = "";
        if(durationTillNow.equals(0L)){
            durationTillNow = DatetimeUtils.getDurationTillNow(createTime, TimeMeasurementUnit.SECOND);
            msg = "您已在" + durationTillNow + "秒前成功制作申请，不可重复制作！";
        }else{
            msg = "您已在" + durationTillNow + "分钟前成功制作申请，不可重复制作！";
        }
        throw new BusinessException(msg);
    }
    @PostMapping("/getMyTodayThreeProgressVisit")
    public ResponseResult getMyTodayThreeProgressVisit(@RequestBody String unionId) {
        return ResponseResult.ok(service.getMyTodayThreeProgressVisit(unionId));
    }
    @PostMapping("/pdf/{visitId}")
    public ResponseResult getPdfFile(@PathVariable Integer visitId) throws IOException, InvalidFormatException {
        return ResponseResult.ok(service.exportPdf(visitId));
    }
    @PostMapping("/word/{visitId}")
    public ResponseResult getWordFile(@PathVariable Integer visitId) throws IOException, InvalidFormatException {
        return ResponseResult.ok(service.exportWord(visitId));
    }
    @PostMapping("/insert")
    public ResponseResult insert(@RequestBody Visit record){
        return ResponseResult.ok(service.insert(record));
    }
    @PostMapping("/delete/{id}")
    public ResponseResult delete(@PathVariable Integer id){
        return ResponseResult.ok(service.delete(id));
    }
    @PostMapping("/update")
    public ResponseResult update(@RequestBody Visit record){
        return ResponseResult.ok(service.update(record));
    }
    @PostMapping("/get8DateRange")
    public ResponseResult get8DateRange(@RequestBody Map<String, LocalDateTime> params){
        LocalDateTime sdate = params.get("sdate");
        LocalDateTime edate = params.get("edate");
        return ResponseResult.ok(service.get8DateRange(sdate,edate));
    }
    @PostMapping("/getMonthList8OpenId")
    public ResponseResult getMonthList8OpenId(@RequestBody GetMonthList8OpenId param) throws Exception {
        return ResponseResult.ok(service.getMonthList8OpenId(param.getUnionId(),param.getDate()));
    }
    @PostMapping("/setVoid/{id}")
    public ResponseResult setVoid(@PathVariable Integer id) throws Exception {
        return ResponseResult.ok(service.setVoid(id));
    }

    /**
     * 审核一个访单要求传入审核人的 unionId
     * 小程序中页面 mill 中审核调用本接口
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("/audit")
    public ResponseResult audit(@RequestBody Map<String,Object> param) throws Exception {
        String unionId = (String) param.get("unionId");
        Integer id = Integer.parseInt(param.get("id").toString());
        return ResponseResult.ok(service.audit(unionId, id));
    }

    /**
     * 审核、驳回都可以使用的API。替代之前的API：visit/audit
     * 2025年1月2日 11:14:10 调整为本接口只应用于审核
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("/auditReject")
    public ResponseResult audit01(@RequestBody Map<String,Object> param) throws Exception {
        String unionId = (String) param.get("unionId");
        Integer id = Integer.parseInt(param.get("id").toString());
        Integer audit = Integer.parseInt(param.get("audit").toString());
        return ResponseResult.ok(service.audit(unionId, id, audit));
    }

    /**
     * 受访者驳回一个访单
     * @param record visit对象，3个必填属性：id,unionId,rejectRemark
     * @return
     * @throws Exception
     */
    @PostMapping("/reject")
    public ResponseResult reject(@RequestBody Visit record) throws Exception {
        return ResponseResult.ok(service.reject(record));
    }

    /**
     * 门卫处扫描二维码，其内容是字段 qr_code.id
     * @param visitId 访单的主键 = visit.id
     * @return 修改访单影响的行数
     * @throws Exception
     */
    @PostMapping("/scanEnterQrCode")
    public ResponseResult scanEnterQrCode(@RequestBody Integer visitId) throws Exception {
        return ResponseResult.ok(service.scanEnterQrCode(visitId));
    }
    @PostMapping("/getVisit4Doorman")
    public ResponseResult getVisit4Doorman() throws Exception {
        return ResponseResult.ok(service.getVisit8Progress(VisitProgress.AUDITED.getSid()));
    }
    @PostMapping("/getVisit4DoormanAll")
    public ResponseResult getVisit4DoormanAll() throws Exception {
        return ResponseResult.ok(service.getVisit8ProgressAll());
    }

    /**
     * 获取进行中的访单，访单综合管理，第一个标签页的数据源
     * @return
     * @throws Exception
     */
    @PostMapping("/getVisitInProgress")
    public ResponseResult getVisitInProgress() {
        return ResponseResult.ok(service.getVisitInProgress());
    }

    /**
     * 获取已完成的访单，访单综合管理，第二个标签页的数据源
     * @return
     */
    @PostMapping("/getVisitFinishedProgress")
    public ResponseResult getVisitFinishedProgress(@RequestBody Map<String, LocalDate> params) {
        LocalDate sdate = params.get("sdate");
        LocalDate edate = params.get("edate");
        return ResponseResult.ok(service.getVisitFinishedProgress(sdate, edate));
    }
    @PostMapping("/getVisitStatistics")
    public ResponseResult getVisitStatistics(@RequestBody String unionId) {
        return ResponseResult.ok(service.getVisitStatistics(unionId));
    }
    @PostMapping("/setFinishedSimple/{visitId}")
    public ResponseResult setFinishedSimple(@PathVariable Integer visitId) {
        return ResponseResult.ok(service.finishVisit(visitId));
    }

    /**
     * 必填3个属性：id - 访单主键，finished - 1表示完工，0取消完工，finished_union_id - 设置完工的微信用户
     * @param record
     * @return
     */
    @PostMapping("/setFinished")
    public ResponseResult setFinished(@RequestBody Visit record) {
        return ResponseResult.ok(service.finishVisit(record));
    }
    @PostMapping("/setLeave/{id}")
    public ResponseResult setLeave(@PathVariable Integer id) {
        return ResponseResult.ok(service.setLeave(id));
    }
    @PostMapping("/getLastVisit8RealName")
    public ResponseResult getLastVisit8RealName(@RequestBody String realName) {
        return ResponseResult.ok(service.getLastVisit8RealName(realName));
    }
    @PostMapping("/insertnull")
    public ResponseResult insertnull(@RequestBody String unionId) {
        return ResponseResult.ok(service.insertNull(unionId));
    }
    @PostMapping("/scanEntryQrcode")
    public ResponseResult scanEntryQrcode(@RequestBody String qrScene) {
        return ResponseResult.ok(service.scanEntryQrcode(qrScene));
    }
    @PostMapping("/getLastSubrogate8RealName")
    public ResponseResult getLastSubrogate8RealName(@RequestBody String realName) {
        return ResponseResult.ok(service.getLastSubrogate8RealName(realName));
    }
    @PostMapping("/getLastVisit8UnionId")
    public ResponseResult getLastVisit8UnionId(@RequestBody Map<String,Object> params) {
        String unionId = params.get("unionId").toString();
        Integer subrogate = Integer.valueOf(params.get("subrogate").toString());
        return ResponseResult.ok(service.getLastVisit8UnionId(unionId,subrogate));
    }
    @PostMapping("/selectOneById/{id}")
    public ResponseResult insert(@PathVariable Integer id){
        return ResponseResult.ok(service.selectOneById(id));
    }

    /**
     * 设置访单为已入场的状态
     * @param id 访单主键 = visit.id
     * @return
     */
    @PostMapping("/setEntry/{id}")
    public ResponseResult setEntry(@PathVariable Integer id) {
        return ResponseResult.ok(service.setEntry(id));
    }
    @PostMapping("/getVisit8ProgressRecent")
    public ResponseResult getVisit8ProgressRecent(@RequestBody Map<String,String> params){
        String unionId = params.get("unionId");
        String progress = params.get("progress");
        return ResponseResult.ok(service.getVisit8ProgressRecent(unionId,progress));
    }
}
